﻿using RedisUtil;
using StackExchange.Redis;
using System;

namespace 并发秒杀系统
{
    /// <summary>
    /// 商品服务
    /// </summary>
    public class ShopService
    {
        /// <summary>
        /// Redis数据库操作
        /// </summary>
        private IDatabase DB;

        /// <summary>
        /// 商品库存key
        /// </summary>
        private string ShopStockKey = "ShopStockKey";

        /// <summary>
        /// 商品是否剩余库存
        /// </summary>
        private bool IsExistShopStock = true;

        public ShopService()
        {
            DB = new BaseRedis().DB;

            // 设置商品库存数量
            DB.StringSet(ShopStockKey, 10);
        }

        /// <summary>
        /// 用户开始秒杀商品
        /// </summary>
        /// <param name="userId"></param>
        public void DecrementShop(string userId)
        {
            if (IsExistShopStock)
            {
                // 向Redis商品库存进行自减操作。如果数量小于0，则活动结束。此操作是原子性操作，可以避免手动lock
                long shopStock = DB.StringDecrement(ShopStockKey);

                if (shopStock < 0)
                {
                    IsExistShopStock = true;
                    Console.WriteLine($"用户ID：{userId}，秒杀失败！库存不足！");
                }
                else
                {
                    Console.WriteLine($"用户ID：{userId}，秒杀成功！库存还剩{shopStock}件商品！");
                }
            }
            else
            {
                Console.WriteLine($"用户ID：{userId}，活动已结束！");
            }
        }
    }
}
